<script setup lang="ts">
import type { ConversationsProps } from 'ant-design-x-vue'
import { ref, createVNode, h, reactive, type PropType, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { Conversations } from 'ant-design-x-vue'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  ToTopOutlined,
  CloseOutlined,
} from '@ant-design/icons-vue'

// 定义事件
const emits = defineEmits(['change', 'top', 'untop', 'rename', 'delete'])

// 外部参数
const props = defineProps({
  // 选项内容
  options: {
    type: Array as PropType<ConversationsProps['items']>,
    required: true,
  },
  // 当前激活的 key
  activeKey: {
    type: [String, Number],
    required: true,
  },
})

// 状态参数
const state = reactive({
  activeKey: undefined,
  isShowModal: false,
})

// 表单数据
const formData = ref({
  key: '',
  title: '',
})

// 菜单
const menuConfig: ConversationsProps['menu'] = (conversation) => {
  return {
    items: [
      {
        label: conversation.isTop ? '取消置顶' : '置顶',
        key: 'top',
        icon: h(conversation.isTop ? CloseOutlined : ToTopOutlined),
      },
      {
        label: '重命名',
        key: 'rename',
        icon: h(EditOutlined),
      },
      {
        label: '删除',
        key: 'delete',
        icon: h(DeleteOutlined),
        danger: true,
      },
    ],
    onClick: (menuInfo) => {
      switch (menuInfo.key) {
        case 'top':
          if (conversation.isTop) {
            // 取消置顶
            emits('untop', conversation.key)
          } else {
            // 置顶
            emits('top', conversation.key)
          }
          break
        case 'rename':
          // 重命名
          formData.value.key = conversation.key
          formData.value.title = conversation.title
          state.isShowModal = true
          break
        case 'delete':
          // 删除
          Modal.confirm({
            title: '永久删除对话',
            icon: createVNode(ExclamationCircleOutlined),
            content: '删除后，该对话将不可恢复。确认删除吗？',
            onOk() {
              emits('delete', conversation.key)
            },
          })
          break
      }
    },
  }
}

// 切换记录
const onActiveChange = (value: string) => {
  state.activeKey = value
  emits('change', value)
}

// 重命名
const handleRename = async () => {
  if (!formData.value.title) {
    message.error('请输入标题')
    return
  }
  emits('rename', formData.value)
  state.isShowModal = false
}

watch(
  () => props.activeKey,
  (key) => {
    state.activeKey = key
  },
  { immediate: true },
)
</script>

<template>
  <div>
    <Conversations
      :activeKey="state.activeKey"
      :menu="menuConfig"
      :groupable="true"
      :items="props.options"
      :on-active-change="onActiveChange"
    />
    <a-modal v-model:open="state.isShowModal" title="重命名" @ok="handleRename">
      <div class="pt-4 pb-4">
        <a-input v-model:value="formData.title" placeholder="请输入标题" />
      </div>
    </a-modal>
  </div>
</template>

<style lang="scss" scoped></style>
